<template>
  <div class="favorites-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的收藏</span>
        </div>
      </template>

      <div v-loading="loading" class="books-grid">
        <div
          v-for="book in favorites"
          :key="book.id"
          class="book-card"
          :class="{ 'out-of-stock': book.stock <= 0 }"
        >
          <div class="book-cover" :style="{ background: getGradientColor(book.id) }">
            <div class="cover-placeholder">
              <el-icon size="60"><Document /></el-icon>
            </div>
            <div v-if="book.stock <= 0" class="stock-badge out">缺货</div>
            <div v-else-if="book.stock <= 3" class="stock-badge low">仅剩{{ book.stock }}本</div>
          </div>
          
          <div class="book-info">
            <h3 class="book-title" :title="book.title">{{ book.title }}</h3>
            <p class="book-author">
              <el-icon><User /></el-icon>
              {{ book.author }}
            </p>
            <div class="book-meta">
              <el-tag v-if="book.category" size="small" type="info">{{ book.category }}</el-tag>
              <span class="stock-info">
                <el-icon><Box /></el-icon>
                库存: {{ book.stock }}
              </span>
            </div>
            <p v-if="book.isbn" class="book-isbn">ISBN: {{ book.isbn }}</p>
            <p v-if="book.description" class="book-description" :title="book.description">
              {{ book.description.length > 60 ? book.description.substring(0, 60) + '...' : book.description }}
            </p>
          </div>

          <div class="book-actions">
            <el-button
              type="primary"
              :disabled="book.stock <= 0"
              @click="handleBorrow(book)"
              class="action-btn"
            >
              <el-icon><ShoppingCart /></el-icon>
              借阅
            </el-button>
            <el-button
              type="danger"
              @click="handleRemoveFavorite(book)"
              class="action-btn"
            >
              <el-icon><StarFilled /></el-icon>
              取消收藏
            </el-button>
          </div>
        </div>

        <el-empty v-if="!loading && favorites.length === 0" description="暂无收藏" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, User, Box, ShoppingCart, StarFilled } from '@element-plus/icons-vue'
import { favoriteAPI, borrowAPI } from '../services/api'

const favorites = ref([])
const loading = ref(false)

const fetchFavorites = async () => {
  loading.value = true
  try {
    const response = await favoriteAPI.getFavorites()
    favorites.value = response.books || []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

const handleBorrow = async (book) => {
  try {
    await ElMessageBox.confirm(`确定要借阅《${book.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await borrowAPI.borrowBook(book.id)
    ElMessage.success('借阅成功')
    await fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '借阅失败')
    }
  }
}

const handleRemoveFavorite = async (book) => {
  try {
    await ElMessageBox.confirm(`确定要取消收藏《${book.title}》吗？`, '确认取消收藏', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await favoriteAPI.removeFavorite(book.id)
    ElMessage.success('取消收藏成功')
    await fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '取消收藏失败')
    }
  }
}

// 生成不同颜色的渐变背景
const getGradientColor = (id) => {
  const gradients = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)'
  ]
  return gradients[id % gradients.length]
}

onMounted(() => {
  fetchFavorites()
})
</script>

<style scoped>
.favorites-container {
  height: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  min-height: 400px;
}

.book-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.book-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.book-card.out-of-stock {
  opacity: 0.7;
}

.book-cover {
  position: relative;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-placeholder {
  color: rgba(255, 255, 255, 0.9);
}

.stock-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.stock-badge.out {
  background: rgba(245, 108, 108, 0.9);
}

.stock-badge.low {
  background: rgba(255, 193, 7, 0.9);
}

.book-info {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.book-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  min-height: 50px;
}

.book-author {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.book-isbn {
  color: #909399;
  font-size: 12px;
  margin: 0;
}

.book-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.stock-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.book-description {
  color: #909399;
  font-size: 13px;
  line-height: 1.6;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-actions {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
}

@media (max-width: 768px) {
  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
  }
}
</style>

